package com.hunan.api.catv.service.biz.attention;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hunan.api.catv.common.ConstantsMsg;
import com.hunan.api.catv.entity.ServiceResult;
import com.hunan.api.catv.entity.dto.AttentionRecordDto;
import com.hunan.api.catv.entity.dto.MemberAttentionDto;
import com.hunan.api.catv.entity.enums.TpnsContentType;
import com.hunan.api.catv.entity.po.Member;
import com.hunan.api.catv.entity.po.MemberAttentionRecord;
import com.hunan.api.catv.entity.vo.NewsVo;
import com.hunan.api.catv.service.ResultService;
import com.hunan.api.catv.service.biz.comment.CommentBiz;
import com.hunan.api.catv.service.biz.like.MemberLikeBiz;
import com.hunan.api.catv.service.biz.news.NewsBiz;
import com.hunan.api.catv.service.impl.attention.AttentionRecordService;
import com.hunan.api.catv.utils.PageUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: wangchao
 * @Date: 2020/12/1 9:18
 */
@Service
public class AttentionRecordBiz extends ResultService {

    @Autowired
    AttentionRecordService attentionRecordService;

    @Autowired
    CommentBiz commentBiz;

    @Autowired
    NewsBiz newsBiz;

    @Value("${attention.counts}")
    private Integer attentionCounts;

    @Autowired
    MemberLikeBiz memberLikeBiz;


    /**
     * 获取用户下关注列表
     * 1、  无关注列表时
     * 每次拉取10位推荐用户信息
     * 推荐规则：
     * 1、 优先推荐编辑配置的推荐关注列表随机推荐
     * 2、 如编辑配置的推荐关注列表数据拉取完成，则在普通用户列表库进行随机推荐
     * <p>
     * 2、  有关注列表时
     * 按作品发布时间降序排列
     */
    public Object getAttentionListByMemberId(Integer memberId, int pageNum, int pageSize) {
        AttentionRecordDto attentionRecordDto = new AttentionRecordDto();
        //获取用户关注用户发布的短视频列表
        PageHelper.startPage(pageNum, pageSize);
        List<MemberAttentionDto> memberAttentionDtoList = attentionRecordService.getNewsListByMemberId(memberId);
        PageInfo<MemberAttentionDto> memberAttentionDtoPageInfo = new PageInfo<>(memberAttentionDtoList);
        memberAttentionDtoList = memberAttentionDtoPageInfo.getList().stream().peek(memberAttentionDto -> {
            Integer newsId = memberAttentionDto.getNewsId();
            NewsVo newsVo = newsBiz.getNewsInfo(newsId);
            BeanUtils.copyProperties(newsVo, memberAttentionDto);
            if (memberId != null) {
                //查询该用户是否点赞该视频
                memberAttentionDto.setLikeState(memberLikeBiz.itemLikeV2(TpnsContentType.news.getCode(), newsId, memberId));
            }
            memberAttentionDto.setCommentVo(commentBiz.getHotCommentsByNewsId(newsId));
        }).collect(Collectors.toList());
        PageInfo<MemberAttentionDto> pageInfo = new PageInfo<>();
        BeanUtils.copyProperties(memberAttentionDtoPageInfo, pageInfo);
        pageInfo.setList(memberAttentionDtoList);
        attentionRecordDto.setAttentionList(memberAttentionDtoPageInfo);
        attentionRecordDto.setAttentionState("1");
        return attentionRecordDto;

    }

    /**
     * 获取推荐关注列表
     */
    public AttentionRecordDto getRecommendAttentionList(int pageNum, int pageSize, Integer memberId) {
        List<MemberAttentionDto> memberAttentionDtoList = new ArrayList<>();
        AttentionRecordDto attentionRecordDto = new AttentionRecordDto();
        //无关注列表 查询默认推荐关注列表
        //List<Member> memberList = new Member().selectList(new QueryWrapper<Member>().ne(Member.MEMBERID,memberId).eq(Member.DEFAULT_ATTENTION, 1).eq(Member.STATE, 1));
        List<Member> memberList = new Member().selectList(new QueryWrapper<Member>().eq(Member.DEFAULT_ATTENTION, 1).eq(Member.STATE, 1)).stream().filter(member -> !memberId.equals(member.getMemberId())).collect(Collectors.toList());
        int size = memberList.size();
        if (size >= attentionCounts) {
            //随机排列列表取前10条数据
            Collections.shuffle(memberList);
            memberAttentionDtoList = getMemberAttentionList(memberList, memberId);
        } else {
            List<Member> unattentionList = new Member().selectList(new QueryWrapper<Member>().ne(Member.MEMBERID, memberId).eq(Member.DEFAULT_ATTENTION, 0).eq(Member.STATE, 1));
            Random random = new Random();
            //随机从不推荐用户关注列表抽取数据
            int i1 = attentionCounts - size;
            //存储随机取出来的随机数
            List<Integer> indexList = new ArrayList<>();
            for (int i = 0; i < i1; i++) {
                int n = random.nextInt(unattentionList.size());
                if (!indexList.contains(n)) {
                    indexList.add(n);
                    memberList.add(unattentionList.get(n));
                } else {
                    i--;
                }
            }
            memberAttentionDtoList = getMemberAttentionList(memberList, memberId);
        }
        PageInfo<MemberAttentionDto> memberAttentionDtoPageInfo = PageUtils.startPage(memberAttentionDtoList, pageNum, pageSize);
        attentionRecordDto.setAttentionState("0");
        attentionRecordDto.setAttentionList(memberAttentionDtoPageInfo);
        return attentionRecordDto;
    }

    private List<MemberAttentionDto> getMemberAttentionList(List<Member> memberList, Integer memberId) {
        return memberList.stream().limit(attentionCounts).map(member -> {
            MemberAttentionDto memberAttentionDto = new MemberAttentionDto();
            if (memberId != null) {
                MemberAttentionRecord memberAttentionRecord = new MemberAttentionRecord().selectOne(new QueryWrapper<MemberAttentionRecord>().eq(MemberAttentionRecord.MEMBER_ID, memberId).eq(MemberAttentionRecord.ATTENTION_ID, member.getMemberId()));
                memberAttentionDto.setAttentionState(memberAttentionRecord != null ? String.valueOf(memberAttentionRecord.getStatus()) : "0");
            }
            memberAttentionDto.setAvatarUrl(member.getAvatarUrl());
            memberAttentionDto.setNickName(member.getNickName());
            memberAttentionDto.setMemberId(member.getMemberId());
            return memberAttentionDto;
        }).collect(Collectors.toList());
    }


    /**
     * 关注/取关
     */
    public Object followOrCheckOff(Integer memberId, MemberAttentionRecord memberAttentionRecord) {
        MemberAttentionRecord memberAttentionRecord1 = new MemberAttentionRecord().selectOne(new QueryWrapper<MemberAttentionRecord>()
                .eq(MemberAttentionRecord.ATTENTION_TYPE, memberAttentionRecord.getAttentionType())
                .eq(MemberAttentionRecord.MEMBER_ID, memberId)
                .eq(MemberAttentionRecord.ATTENTION_ID, memberAttentionRecord.getAttentionId()));
        if (memberAttentionRecord1 != null) {
            memberAttentionRecord.setId(memberAttentionRecord1.getId()).setStatus(memberAttentionRecord1.getStatus() == 0 ? 1 : 0).setUpdateTime(new Date());
        } else {
            memberAttentionRecord.setStatus(1).setMemberId(memberId).setCreateTime(new Date());
        }
        boolean resultState = memberAttentionRecord.insertOrUpdate();
        log.info("关注/取关状态更改:{}", resultState);
        //查询该用户是否关注过用户
        boolean checkAttentionState = checkAttention(memberId);
        HashMap<Object, Object> map = new HashMap<>(16);
        map.put("resultState", resultState);
        map.put("checkAttentionState", checkAttentionState);
        return map;
    }

    /**
     * 校验关注
     */
    public boolean checkAttention(Integer memberId) {
        List<MemberAttentionRecord> memberAttentionRecordList = new MemberAttentionRecord().selectList(new QueryWrapper<MemberAttentionRecord>()
                .select(MemberAttentionRecord.ATTENTION_ID)
                .eq(MemberAttentionRecord.MEMBER_ID, memberId)
                .eq(MemberAttentionRecord.ATTENTION_TYPE, 0)
                .eq(MemberAttentionRecord.STATUS, 1)
        );
        return !CollectionUtils.isEmpty(memberAttentionRecordList);
    }

    /**
     * 判断该用户是否关注
     */
    public ServiceResult checkAttentionByMemberId(Integer memberIdV2, Integer newsId) {
        HashMap<String, Object> map = new HashMap<>(16);
        NewsVo info = newsBiz.info(newsId);
        if (info == null) {
            return buildFail(ConstantsMsg.NEWS_SELECT_FAIL);
        }
        if (memberIdV2.equals(info.getMemberId())) {
            //登录人和关注人一致
            map.put("type", 1);
            return buildOK(map);
        }
        //判断是否关注这用户
        MemberAttentionRecord memberAttentionRecord = new MemberAttentionRecord().selectOne(new QueryWrapper<MemberAttentionRecord>()
                .eq(MemberAttentionRecord.MEMBER_ID, memberIdV2)
                .eq(MemberAttentionRecord.ATTENTION_ID, info.getMemberId())
                .eq(MemberAttentionRecord.ATTENTION_TYPE, 0)
        );
        //登录人和关注人不一致
        map.put("type", 2);
        map.put("attentionStatus", memberAttentionRecord != null && (memberAttentionRecord.getStatus() != 0));
        return buildOK(map);
    }
}
